package com.ydj.framework.controller;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.ydj.framework.annotation.AllowGuest;
import com.ydj.framework.exception.CommonException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Map;

/**
 * @author rick
 */
@Slf4j
@RestController
@RequestMapping("/common/proxy")
@Api(tags = "所有项目-共用代理请求")
public class FwCommonProxyController {
    private final RestTemplate restTemplate;

    public FwCommonProxyController(RestTemplateBuilder restTemplateBuilder) {
        this.restTemplate = restTemplateBuilder.build();
    }

    @AllowGuest
    @ApiOperation(value = "代理跨域URL Get")
    @ApiOperationSupport(order = 11)
    @GetMapping("/get")
    public ResponseEntity<String> proxyGet(@RequestParam String url, @RequestHeader HttpHeaders headers) {
        // 代理GET请求并转发头部
        HttpEntity<Void> entity = new HttpEntity<>(headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
        return ResponseEntity.status(response.getStatusCode()).body(response.getBody());
    }

    @AllowGuest
    @ApiOperation(value = "代理跨域URL Post")
    @ApiOperationSupport(order = 12)
    @PostMapping("/post")
    public ResponseEntity<String> proxyPost(@RequestParam String url, @RequestBody String body, @RequestHeader HttpHeaders headers) throws CommonException {
        URI uri;
        try {
            uri = new URI(url);
        } catch (URISyntaxException e) {
            CommonException.throwException("URL解析错误.具体错误是" + e.getMessage());
            return null;
        }
        String host = uri.getHost();
        headers.set(HttpHeaders.HOST, host);

        // 代理POST请求并转发头部
        HttpEntity<String> entity = new HttpEntity<>(body, headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        return ResponseEntity.status(response.getStatusCode()).body(response.getBody());
    }
}